package jwtutils

import (
	"fmt"
	"time"

	jwt "github.com/golang-jwt/jwt/v4"
)

var jwtKey = []byte("liuwa")

type LiuWaClaims struct {
	jwt.RegisteredClaims
	Username string `json:"username"`
	UserId   string
}

func GeneratoToken(userName string, userId string) (string, error) {
	fmt.Println("GeneratoToke")

	liuWaClaims := LiuWaClaims{
		Username: userName,
		UserId:   userId,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24 * 7)),
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, liuWaClaims)
	return token.SignedString(jwtKey)
}

func ValidateJWT(tokenStr string) (*LiuWaClaims, error) {

	token, err := jwt.ParseWithClaims(tokenStr, &LiuWaClaims{}, func(t *jwt.Token) (interface{}, error) {
		return jwtKey, nil
	})

	if claims, ok := token.Claims.(*LiuWaClaims); ok && token.Valid {
		return claims, nil
	} else {
		return nil, err
	}
}
